<template>
	<view class="specs">
        <view class="specs-view" @click="specsShow = true">
            <view>
                <text class="bold-text">已选</text>
            </view>
            <view class="content-view u-margin-left-20">
                <text>{{ selectedSku ? selectedSpecVals.join('-') : '未选规格' }} {{buyNum}}个</text>
            </view>
            <view>
                <u-icon class="collection-icon u-margin-right-10" name="more-dot-fill" size="36"></u-icon>
            </view>
        </view>
        <!-- 商品规格弹出层 -->
        <u-popup v-model="specsShow" mode="bottom" length="70%" closeable close-icon-size="20" border-radius="20" class="goods-popup-header">
            <view class="specs-headr u-p-20">
                <u-image width="200rpx" height="200rpx" :src="selectedSpecImg.thumbnail || selectedSku.thumbnail || goods.thumbnail"></u-image>
                <view class="price-header">
                    <view class="price-text" v-if="promotionsPrice">
                        {{ promotionsPrice }}
                    </view>
                    <view class="price-text" v-else-if="assemble.id">
                        {{ assemble.sales_price | unitPrice('￥') }}
                    </view>
                    <view class="price-text" v-else>
                        {{ selectedSku.price | unitPrice('￥') }}
                    </view>
                    <!-- <custom-price v-else :price="selectedSku.price" :textColor="'#FF0000'" :fontWeight="600" :size="35"></custom-price> -->
                    <view class="u-m-t-10">
                        <text class="specs-name">已选</text>
                        <text class="specs-value">{{selectedSku ? selectedSpecVals.join('-') : '未选规格'}} {{buyNum}}个</text>
                    </view>
                </view>
            </view>
            <scroll-view scroll-y="true" class="specs-body" >
                <view class="specs-list u-p-20" v-for="(spec, specIndex) in specList" :key="specIndex">
                    <view>
                        <text class="bold-text">{{spec.spec_name}}</text>
                    </view>
                    <view class="u-p-t-30">
                        <u-button
                            v-for="(spec_val, index) in spec.valueList"
                            :key="index"
                            size="mini"
                            class="u-m-r-30"
                            shape="circle"
                            :plain="true"
                            hover-class="none"
                            :type="spec_val.selected ? 'error' : 'default'"
                            @click="handleClickSpec(spec, specIndex, spec_val)"
                            throttle-time="10"
                            :custom-style="specStyle"
                        >
                            {{spec_val.spec_value}}
                        </u-button>
                    </view>
                </view>
                <view class="u-padding-20 u-flex u-row-between">
                    <text class="bold-text">数量</text>
                    <u-number-box v-model="buyNum" :min="1" :max="selectedSku.enable_quantity" @change="handleBuyNum"></u-number-box>
                </view>
            </scroll-view>
            <view class="specs-footer u-flex">
                <view v-if="buyNum === 0" class="inventory btn u-line-1 u-flex-1">暂无库存</view>
                <view v-if="buyNum !== 0" class="cart btn u-line-1 u-text-center u-flex-1" @click="$emit('add-cart')">加入购物车</view>
                <view v-if="buyNum !== 0" class="buy btn u-line-1 u-text-center u-flex-1" @click="$emit('buy-now')">立即购买</view>
            </view>
        </u-popup>
	</view>
</template>

<script>
import * as API_Goods from '@/api/goods.js'
import { Foundation } from '@/ui-utils/index.js'

export default {
  data() {
    return {
      specsShow: false,
      // 购买数量
      buyNum: 1,
      // skuMap
      skuMap: new Map(),
      // 规格列表
      specList: [],
      // 被选中规格
      selectedSpec: [],
      selectedSpecVals: [],
      // 规格组合列表
      skusCombination: [],
      // 被选中sku
      selectedSku: '',
      // 被选中的规格图片【如果有】
      selectedSpecImg: '',
      // 没有选中sku，初始化为false
      unselectedSku: false,
      // 商品原价
      promotionsPrice: false,
      specStyle: {
        padding: '20rpx 40rpx',
        fontWeight: 600,
      }
    }
  },
  props: {
    goods: {
      type: Object,
      default() {
        return {}
      }
    },
    promotions: {
      type: Array,
      default() {
        return []
      }
    },
    sku_id: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    },
    assemble: {
      type: Object,
      default: ''
    }
  },
  watch: {
    show(newVal) {
      this.specsShow = newVal
    },
    specsShow(newVal) {
      this.$emit('close', newVal)
    },
    selectedSku(newVal) {
      this.$emit('sku-changed', newVal)
    },
    buyNum(newVal) {
      this.$emit('num-changed', newVal)
    },
    promotions(newVal) {
      const _promotions = newVal.filter(key => key.sku_id === (this.selectedSku.sku_id || this.sku_id))
      const _prom = _promotions.filter(key => key.promotion_type === 'SECKILL' || key.promotion_type === 'GROUPBUY' || key.promotion_type === 'EXCHANGE')

      // 如果是限时抢购或者团购促销活动不显示原价格
      if (_prom && _prom[0]) {
        if (_prom[0].promotion_type === 'SECKILL') {
          this.promotionsPrice = `￥${Foundation.formatPrice(_prom[0].seckill_goods_vo.seckill_price)}`
        } else if (_prom[0].promotion_type === 'GROUPBUY') {
          this.promotionsPrice = `￥${Foundation.formatPrice(_prom[0].groupbuy_goods_vo.price)}`
        } else if (_prom[0].promotion_type === 'EXCHANGE') {
          this.promotionsPrice = `${_prom[0].exchange.exchange_point}积分+￥${Foundation.formatPrice(_prom[0].exchange.exchange_money)}`
        } else {
          this.promotionsPrice = false
        }
      }
    }
  },
  beforeMount() {

  },
  created() {
  },
  mounted() {
    API_Goods.getGoodsSkus(this.goods.goods_id).then(responses => {
      const response = responses
      const specList = []
      response.forEach((sku, skuIndex) => {
        const { spec_list } = sku
        const spec_value_ids = []
        let _combination = []
        if (spec_list) {
          spec_list.forEach((spec, specIndex) => {
            const _specIndex = specList.findIndex(_spec => _spec['spec_id'] === spec.spec_id)
            const _spec = {
              spec_id: spec.spec_id,
              spec_name: spec.spec_name,
              spec_type: spec.spec_type
            }
            const _value = {
              spec_value: spec.spec_value,
              spec_value_id: spec.spec_value_id,
              spec_value_index: skuIndex,
              spec_value_img: {
                original: spec.spec_image,
                thumbnail: spec.thumbnail
              }
            }
            _combination.push({ ..._value })
            spec_value_ids.push(spec.spec_value_id)
            if (_specIndex === -1) {
              specList.push({ ..._spec, valueList: [{ ..._value }] })
            } else if (specList[_specIndex]['valueList'].findIndex(_value => _value['spec_value_id'] === spec['spec_value_id']) === -1) {
              specList[_specIndex]['valueList'].push({ ..._value })
            }
          })
          this.skusCombination.push(_combination)
          this.skuMap.set(spec_value_ids.join('-'), sku)
        } else {
          this.skuMap.set('no_spec', sku)
        }
      })
      this.specList = specList
      // 如果有sku信息，初始化已选规格
      if (this.sku_id) {
        this.initSpec()
      } else if (this.specList) {
        //默认选中第一个sku
        const _selectedSpecVals = []
        this.specList.forEach((spec, specIndex) => {
          if (Array.isArray(spec.valueList)) {
            spec.valueList.forEach((val, specValIndex) => {
              if (specValIndex === 0) {
                val.selected = true
                this.selectedSpec[specIndex] = val.spec_value_id
                _selectedSpecVals.push(val.spec_value)
              }
            })
          }
        })
        this.$set(this, 'selectedSpecVals', _selectedSpecVals)
        this.handleSelectedSku(true)
      }
      // 如果没有规格，把商品第一个可选sku给已选择sku
      if (!specList.length) {
        this.selectedSku = this.skuMap.get('no_spec')
      }
    })

  },
  methods: {
    //初始化规格
    initSpec() {
      let selectedSpecs = ''
      if (this.sku_id) {
        this.skuMap.forEach((value, key) => {
          if (value.sku_id === this.sku_id) {
            selectedSpecs = key.split('-')
          }
        })
      }
      const _selectedSpecVals = []
      this.specList.forEach((spec, specIndex) => {
        if (Array.isArray(spec.valueList)) {
          spec.valueList.forEach((val, specValIndex) => {
            if (selectedSpecs) {
              const spec_value_id = val.spec_value_id
              if (selectedSpecs.indexOf(String(spec_value_id)) !== -1) {
                val.selected = true
                this.selectedSpec[specIndex] = val.spec_value_id
                _selectedSpecVals.push(val.spec_value)
              }
            } else if (specValIndex === 0) {
              val.selected = true
              this.selectedSpec[specIndex] = val.spec_value_id
              _selectedSpecVals.push(val.spec_value)
            }
          })
        }
      })
      this.$set(this, 'selectedSpecVals', _selectedSpecVals)
      this.handleSelectedSku()
    },
    //选择规格
    handleClickSpec(spec, specIndex, spec_val) {
      if (spec.spec_type === 1) {
        this.selectedSpecImg = JSON.parse(JSON.stringify(spec_val.spec_value_img))
      }
      if (spec_val.selected) return
      spec.valueList.map(item => {
        item.selected = item.spec_value_id === spec_val.spec_value_id
        return item
      })
      this.$set(this.specList, specIndex, spec)
      this.selectedSpec[specIndex] = spec_val.spec_value_id
      this.selectedSpecVals[specIndex] = spec_val.spec_value
      this.handleSelectedSku(true)
    },
    //根据已选规格选出对应的sku
    handleSelectedSku(falg) {
      let sku
      if (this.selectedSpec.length) {
        const spec_vals = []
        this.selectedSpec.forEach(item => spec_vals.push(item))
        sku = this.skuMap.get(spec_vals.join('-'))
      } else {
        sku = this.skuMap.get('no_spec')
      }
      if (sku) {
        this.selectedSku = sku
        this.unselectedSku = false
        this.goodsInfo = { ...this.goodsInfo, ...sku }
        this.buyNum = sku.enable_quantity === 0 ? 0 : 1
        if (falg) {
          if (!this.promotions || !this.promotions.length) return
          const _promotions = this.promotions.filter(key => key.sku_id === (this.selectedSku.sku_id || this.sku_id))
          if (_promotions) {
            let _prom = _promotions.filter(key => key.promotion_type === 'GROUPBUY' || key.promotion_type === 'SECKILL')
            if (_prom && _prom[0] && _prom[0].promotion_type === 'GROUPBUY') {
              this.promotionsPrice = `￥${Foundation.formatPrice(_prom[0].groupbuy_goods_vo.price)}`
            } else if (_prom && _prom[0] && _prom[0].promotion_type === 'SECKILL') {
              this.promotionsPrice = `￥${Foundation.formatPrice(_prom[0].seckill_goods_vo.seckill_price)}`
            } else {
              this.promotionsPrice = false
            }
          }
        }
      }
    },
    //购买数量
    handleBuyNum(e) {
      this.buyNum = e.value
    }
  }
}
</script>

<style lang="scss" scoped>
.specs {
  border-radius: 15rpx;
  margin-top: 23rpx;
  background-color: #FFFFFF;
  .specs-view {
    padding: 30rpx;
    display: flex;
    align-items: center;
    padding-bottom: 20rpx;
    .left-view {
      margin-right: 20rpx;
    }
    .bold-text {
      font-weight: bold;
    }
    .content-view {
      flex: 1;
    }
  }
  //规格选择器弹出框
  .goods-popup-header {
    .specs-headr {
      display: flex;
      flex-direction: row;
      background-color: #FFFFFF;
      height: 240rpx;
      width: 100%;
      .price-header {
        margin-left: 30rpx;
        margin-top: 80rpx;
        .price-text {
          font-size: 45rpx;
          font-weight: bold;
          color: #ff5000;
          margin-top: 20rpx;
        }
        .specs-name {
          color: #909399;
          margin-right: 10rpx;
        }
        .specs-value {
          font-weight: 400;
        }
      }
    }
    .specs-body {
      // height: calc(100vh - 750rpx);
      height: 570rpx;
      // #ifdef MP
      height: 500rpx;
      // #endif
      overflow-x: hidden;
    }
    .specs-footer {
      width: 100%;
      position: fixed;
      left: 0;
      bottom: 0;
      z-index: 999;
      color: #FFFFFF;
      border-top: 2rpx solid #f3f4f6;
      font-size: 28rpx;
      padding: 0rpx 20rpx;
      padding-bottom: 60rpx;
      padding-top: 10rpx;
      .btn {
        line-height: 80rpx;
        padding: 0 30rpx;
        text-align: center;
      }
      .inventory {
        filter: opacity(0.7);
        border-radius: 40rpx;
        background: linear-gradient(to right, #FFCA1E 0%, #EF0D25 100%);
      }
      .cart {
        border-top-left-radius: 40rpx;
        border-bottom-left-radius: 40rpx;
        background: linear-gradient(to right, #FFCA1E 0%, #FF8B18 100%);
      }
      .buy {
        border-top-right-radius: 40rpx;
        border-bottom-right-radius: 40rpx;
        background: linear-gradient(to right, #FD5632 0%, #EF0D25 100%);
      }
    }
  }
}
</style>
